package com.kuanter.kuanterauto.website;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextPaint;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.ItemizedOverlay;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKMapViewListener;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.baidu.mapapi.OverlayItem;
import com.kuanter.kuanterauto.HomeActivityGroup;
import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.MapResult;
import com.kuanter.kuanterauto.entity.WebSiteInfo;
import com.kuanter.kuanterauto.entity.WebSiteInfoList;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.net.HttpUtil;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;

public class WebSiteActivity extends MapActivity {

	static View mPopView = null; // 点击mark时弹出的气泡View
	static MapView mMapView = null;
	LocationListener mLocationListener = null;// onResume时注册此listener，onPause时需要Remove
	MyLocationOverlay mLocationOverlay = null; // 定位图层

	static String distance = null;
	static int selectIndex = -1;

	static List<WebSiteInfo> webSiteInfo = null;

	static TextView popviewTitle = null;
	Button huidao = null;
	static TextView popviewSubTitle = null;
	static TextView tv_distance = null;
	static Location locData = null;

	boolean locFlag = true;
	boolean requestFlag = true;
	int requestTimeFlag = 0;
	int parseTimeFlag = 0;
	boolean destroyFlag = false;
	static int zoomLevel = 16;
	
	DataLoader loader=null;
	
	long startMove;
	long endMove;
	
	
	

	// 存放overlayitem
	static List<OverlayItem> mGeoList = new ArrayList<OverlayItem>();

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {

			parseTimeFlag++;
			if ((requestTimeFlag != parseTimeFlag) || (destroyFlag)){
				return;
			}

			switch (msg.what) {
			case 1:
				Bundle bundle = msg.getData();
				String json = bundle.getString("result");
//				 System.out.println("---------------------" + json);
				try {
					if (!StringUtils.isSuccess(json)) {
						Toast.makeText(WebSiteActivity.this,
								"service return date false", Toast.LENGTH_SHORT)
								.show();
						return;
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				WebSiteInfoList info = new WebSiteInfoList(json);
				webSiteInfo = info.getWebSiteInfos();
				if(webSiteInfo == null)
					return;
				mGeoList.clear();
				System.out.println("---------" + webSiteInfo.size());
				for (int i = 0; i < webSiteInfo.size(); i++) {
					WebSiteInfo webSiteItem = webSiteInfo.get(i);

					GeoPoint p = new GeoPoint(
							(int) (Double.parseDouble(webSiteItem
									.getyCoordinates()) * 1E6),
							(int) (Double.parseDouble(webSiteItem
									.getxCoordinates()) * 1E6));

					OverlayItem item = new OverlayItem(p,
							webSiteItem.getShopName(), webSiteItem.getQueue());
					if (webSiteItem.getQueue().equals("1")) {
						item.setMarker(getResources().getDrawable(
								R.drawable.green));
					} else if (webSiteItem.getQueue().equals("2")) {
						item.setMarker(getResources().getDrawable(
								R.drawable.yellow));
					} else {
						item.setMarker(getResources().getDrawable(
								R.drawable.red));
					}
					mGeoList.add(item);
				}

				addWebSiteItem();
				break;
			case -1:
//				Bundle bundle2 = msg.getData();
//				String json2 = bundle2.getString("result");
//				Toast.makeText(WebSiteActivity.this, "网络连接错误",
//						Toast.LENGTH_SHORT).show();
				break;
			}
		};
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.website);
		loader=new DataLoader(this);
		

		HomeActivityGroup.mBMapMan.start();
		// 如果使用地图SDK，请初始化地图Activity
		super.initMapActivity(HomeActivityGroup.mBMapMan);

		mMapView = (MapView) findViewById(R.id.bmapsView);
//		mMapView.setBuiltInZoomControls(true);
		// 设置在缩放动画过程中也显示overlay,默认为不绘制
		mMapView.setDrawOverlayWhenZooming(true);
		mMapView.getController().setZoom(16);

		// 添加定位图层
		mLocationOverlay = new MyLocationOverlay(this, mMapView);
		mMapView.getOverlays().add(mLocationOverlay);
		mLocationOverlay.disableCompass();
		
		// 注册定位事件
		mLocationListener = new LocationListener() {

			@Override
			public void onLocationChanged(Location location) {
				if (location != null) {
					if (locFlag) {
						GeoPoint pt = new GeoPoint(
								(int) (location.getLatitude() * 1e6),
								(int) (location.getLongitude() * 1e6));
						
						 mMapView.getController().setCenter(pt);
						
//						mMapView.getController().setCenter(
//								new GeoPoint((int) (30.602651* 1e6),
//										(int) (114.220378 * 1e6)));
						requestWebSite();
						locFlag = false;

						// System.out.println(location.getLatitude()+"--"+location.getLongitude());
//						System.out.println("onLocationChanged:"
//								+ mMapView.getMapCenter().getLatitudeE6() + "-"
//								+ mMapView.getMapCenter().getLongitudeE6()
//								+ "+++++++++++" + mMapView.getLatitudeSpan()
//								+ "-" + mMapView.getLongitudeSpan());

						requestFlag = false;

					}

					locData = location;
				}
			}
		};
		

		

		// 添加ItemizedOverlay
		Drawable marker = getResources().getDrawable(R.drawable.red); // 得到需要标在地图上的资源
		marker.setBounds(0, 0, marker.getIntrinsicWidth(),
				marker.getIntrinsicHeight()); // 为maker定义位置和边界

		// 创建点击mark时的弹出泡泡
		mPopView = super.getLayoutInflater().inflate(R.layout.popview, null);
		popviewTitle = (TextView) mPopView.findViewById(R.id.title);
		TextPaint paint = popviewTitle.getPaint();
		paint.setFakeBoldText(true);
		popviewSubTitle = (TextView) mPopView.findViewById(R.id.subtitle);
		tv_distance = (TextView) mPopView.findViewById(R.id.tv_distance);
		mMapView.addView(mPopView, new MapView.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, null,
				MapView.LayoutParams.TOP_LEFT));
		mPopView.setVisibility(View.GONE);
		mPopView.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				bundle.putString("shopName", webSiteInfo.get(selectIndex)
						.getShopName());
				bundle.putString("shopImage", webSiteInfo.get(selectIndex)
						.getShopImage());
				bundle.putString("shopAddress", webSiteInfo.get(selectIndex)
						.getShopAddress());
				bundle.putString("phone", webSiteInfo.get(selectIndex)
						.getShopPhone());
				bundle.putString("xCoordinates", webSiteInfo.get(selectIndex)
						.getxCoordinates());
				bundle.putString("yCoordinates", webSiteInfo.get(selectIndex)
						.getyCoordinates());
				bundle.putString("queue", webSiteInfo.get(selectIndex)
						.getQueue());
				bundle.putString("bigcarPoint", webSiteInfo.get(selectIndex)
						.getBigcarPoint());
				bundle.putString("bigcarPrice", webSiteInfo.get(selectIndex)
						.getBigcarPrice());
				bundle.putString("smallcarPoint", webSiteInfo.get(selectIndex)
						.getSmallcarPoint());
				bundle.putString("smallcarPrice", webSiteInfo.get(selectIndex)
						.getSmallcarPrice());
				if (distance != null)
					bundle.putString("distance", distance);
				intent.putExtras(bundle);
				intent.setClass(WebSiteActivity.this,
						WebSiteDetailActivity.class);
				startActivity(intent);

			}
		});

		mMapView.regMapViewListener(HomeActivityGroup.mBMapMan,
				new MKMapViewListener() {
			
					public void onMapMoveFinish() {
						// 此处可以实现地图移动完成事件的状态监听
						if (!requestFlag) {
							mPopView.setVisibility(View.GONE);
							requestWebSite();
//							System.out.println("onMapMoveFinish:"
//									+ mMapView.getMapCenter().getLatitudeE6()
//									+ "-"
//									+ mMapView.getMapCenter().getLongitudeE6()
//									+ "+++++++++++"
//									+ mMapView.getLatitudeSpan() + "-"
//									+ mMapView.getLongitudeSpan());

						}
					}
				});

		huidao = (Button) findViewById(R.id.huidao);
		huidao.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (locData != null) {
					mMapView.getController().setCenter(
							new GeoPoint((int) (locData.getLatitude() * 1e6),
									(int) (locData.getLongitude() * 1e6)));
					requestWebSite();
				}

			}
		});

		//测试代码
//		mMapView.getController()
//				.setCenter(
//						new GeoPoint((int) (30.602651 * 1e6),
//								(int) (114.220378 * 1e6)));
//		requestFlag = false;
		

	}

	@Override
	protected void onDestroy() {
		destroyFlag = true;
//		loader.shutDown();
		System.out.println("map destroy");
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		MobclickAgent.onPause(this);
		if (HomeActivityGroup.mBMapMan != null) {
			HomeActivityGroup.mBMapMan.getLocationManager().removeUpdates(
					mLocationListener);
			mLocationOverlay.disableMyLocation();
			// mLocationOverlay.disableCompass(); // 关闭指南针
			HomeActivityGroup.mBMapMan.stop();

		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		MobclickAgent.onResume(this);
		if (HomeActivityGroup.mBMapMan != null) {

			// 注册定位事件，定位后将地图移动到定位点
			HomeActivityGroup.mBMapMan.getLocationManager().requestLocationUpdates(
					mLocationListener);
			mLocationOverlay.enableMyLocation();
			// mLocationOverlay.enableCompass(); // 打开指南针
			HomeActivityGroup.mBMapMan.start();
		}
		
		

		super.onResume();
	}

	public String getProxyHost(boolean isDefault) {
		if (!isDefault)
			return android.net.Proxy.getHost(this);
		else
			return android.net.Proxy.getDefaultHost();
	}

	public int getProxyPort(boolean isDefault) {
		if (!isDefault)
			return android.net.Proxy.getPort(this);
		else
			return android.net.Proxy.getDefaultPort();
	}

	public void prepareRun() {
		NetworkInfo info = getNetworkInfo();
		if (info != null) {
			if (info.getType() == ConnectivityManager.TYPE_WIFI) {
				// WIFI: global http proxy
				HttpTask.proxyHost = getProxyHost(false);
				HttpTask.proxyPort = getProxyPort(false);
				if (HttpTask.proxyHost != null
						&& HttpTask.proxyHost.length() > 0
						&& HttpTask.proxyHost
								.equalsIgnoreCase(android.net.Proxy
										.getDefaultHost())) {
					HttpTask.proxyHost = null;
				}
			} else {
				// GPRS: APN http proxy
				HttpTask.proxyHost = getProxyHost(true);
				HttpTask.proxyPort = getProxyPort(true);
			}
		}
	}

	public NetworkInfo getNetworkInfo() {
		ConnectivityManager connMgr = (ConnectivityManager) this
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		return connMgr.getActiveNetworkInfo();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);

	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mMapView.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	public void removeAllItem() {

		mMapView.getOverlays().clear();
		mMapView.getOverlays().add(mLocationOverlay);
	}

	public void RemoveItem(int index) {
		mGeoList.remove(index);
		mMapView.getOverlays().remove(index);
	}

	public void addWebSiteItem() {

		removeAllItem();
		if (mGeoList.size() > 0) {
			for (OverlayItem item : mGeoList) {
				Drawable marker = item.getMarker(0);
				OverItemT ov = new OverItemT(marker, this);
				ov.addItem(item);
				mMapView.getOverlays().add(ov);

			}

		}
		mMapView.invalidate();

	}

	public void requestWebSite() {
		System.out.println("requestWebSite");
		List<NameValuePair> p = new ArrayList<NameValuePair>();
		double f1, f2, f3, f4;
		if (mMapView.getZoomLevel() > zoomLevel) {
			f1 = ((double) (mMapView.getMapCenter().getLatitudeE6()
					- mMapView.getLatitudeSpan() + 800)) / 1000000.00d;
			f2 = ((double) (mMapView.getMapCenter().getLongitudeE6()
					- mMapView.getLongitudeSpan() + 800)) / 1000000.00d;
			f3 = ((double) (mMapView.getMapCenter().getLatitudeE6()
					+ mMapView.getLatitudeSpan() - 800)) / 1000000.00d;
			f4 = ((double) (mMapView.getMapCenter().getLongitudeE6()
					+ mMapView.getLongitudeSpan() - 800)) / 1000000.00d;
		} else if (mMapView.getZoomLevel() < zoomLevel) {
			f1 = ((double) (mMapView.getMapCenter().getLatitudeE6()
					- mMapView.getLatitudeSpan() / 4 + 800)) / 1000000.00d;
			f2 = ((double) (mMapView.getMapCenter().getLongitudeE6()
					- mMapView.getLongitudeSpan() / 4 + 800)) / 1000000.00d;
			f3 = ((double) (mMapView.getMapCenter().getLatitudeE6()
					+ mMapView.getLatitudeSpan() / 4 - 800)) / 1000000.00d;
			f4 = ((double) (mMapView.getMapCenter().getLongitudeE6()
					+ mMapView.getLongitudeSpan() / 4 - 800)) / 1000000.00d;
		} else {
			f1 = ((double) (mMapView.getMapCenter().getLatitudeE6()
					- mMapView.getLatitudeSpan() / 2 + 800)) / 1000000.00d;
			f2 = ((double) (mMapView.getMapCenter().getLongitudeE6()
					- mMapView.getLongitudeSpan() / 2 + 800)) / 1000000.00d;
			f3 = ((double) (mMapView.getMapCenter().getLatitudeE6()
					+ mMapView.getLatitudeSpan() / 2 - 800)) / 1000000.00d;
			f4 = ((double) (mMapView.getMapCenter().getLongitudeE6()
					+ mMapView.getLongitudeSpan() / 2 - 800)) / 1000000.00d;
		}
		// String southwestCoord = 114.204666+","+30.542524;
		// String northeastCoord = 114.407037+","+30.646973;
		String southwestCoord = f2 + "," + f1;
		String northeastCoord = f4 + "," + f3;
		p.add(new BasicNameValuePair("southwestCoord", southwestCoord));
		p.add(new BasicNameValuePair("northeastCoord", northeastCoord));

//		HttpTask task = new HttpTask(mHandler, p, this);
//		task.setKey(southwestCoord + "-" + northeastCoord);
//		task.execute(MainConstants.HOST + "shopInfo/query_shop");// url
//		System.out.println("value null");
		if(CheckNetworkState()){
		loader.DisplayData(MainConstants.HOST + "shopInfo/query_shop", p, mHandler,"",false);
		}
//		String s=HttpUtil.requestStringForPost(url, params, this)
//		final List<NameValuePair> pr=p;
//		
//		mHandler.post(new Runnable() {
//			
//			@Override
//			public void run() {
//				
////				Message msg = new Message();
////				Bundle bundle = new Bundle();
////					bundle.putString("result", result);
////					msg.what = HttpTask.RESULT_OK;
////					msg.setData(bundle);
////					mHandler.sendMessage(msg);
//					mHandler.obtainMessage(HttpTask.RESULT_OK).sendToTarget();
//				try {
//					Thread.sleep(1000);
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				}
//			}
//		});

		zoomLevel = mMapView.getZoomLevel();
		requestTimeFlag++;

	}
	
	//判断网络是否可用
	public boolean CheckNetworkState()
    {
        boolean flag = false;
        ConnectivityManager manager = (ConnectivityManager)getSystemService(
                Context.CONNECTIVITY_SERVICE);
        if(manager.getActiveNetworkInfo() != null)
        {
            flag = manager.getActiveNetworkInfo().isAvailable();
        }
        if(!flag)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setIcon(android.R.drawable.ic_dialog_alert);
            builder.setTitle("网络状况");
            builder.setMessage("当前网络不可用，是否设置网络");
            builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    Intent mIntent = new Intent("/");
                    ComponentName comp = new ComponentName("com.android.settings",
                            "com.android.settings.WirelessSettings");
                    mIntent.setComponent(comp);
                    mIntent.setAction("android.intent.action.VIEW");
                    startActivity(mIntent);
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            builder.create();
            builder.show();
        }
        
        return flag;
        
    }


}

class OverItemT extends ItemizedOverlay<OverlayItem> {
	static double DEF_PI = 3.14159265359; // PI
	static double DEF_PI180 = 0.01745329252; // PI/180.0
	static double DEF_2PI = 6.28318530712; // 2*PI
	static double DEF_R = 6370693.5; // radius of earth
	public List<OverlayItem> mGeoList = new ArrayList<OverlayItem>();
	private Drawable marker;
	private Context mContext;

	public OverItemT(Drawable marker, Context context) {
		super(boundCenterBottom(marker));
		this.mContext = context;
		this.marker = marker;
		// populate(); // createItem(int)方法构造item。一旦有了数据，在调用其它方法前，首先调用这个方法
	}

	public void addItem(OverlayItem item) {
		// TODO Auto-generated method stub
		mGeoList.add(item);
		populate();
	}

	public void removeItem(int index) {
		mGeoList.remove(index);
		populate();
	}

	public void updateOverlay() {
		populate();
	}

	@Override
	protected OverlayItem createItem(int i) {
		// TODO Auto-generated method stub
		return mGeoList.get(i);
	}

	@Override
	public int size() {
		// TODO Auto-generated method stub
		return mGeoList.size();
	}

	@Override
	// 处理当点击事件
	protected boolean onTap(int i) {
		// setFocus(mGeoList.get(i));
		for (int j = 0; j < WebSiteActivity.webSiteInfo.size(); j++) {
			if (mGeoList.get(i).getTitle()
					.equals(WebSiteActivity.webSiteInfo.get(j).getShopName())) {
				WebSiteActivity.selectIndex = j;
				break;
			}
		}
		NumberFormat format = NumberFormat.getInstance();
		format.setMaximumFractionDigits(1);
		if (WebSiteActivity.locData != null) {
			float[] dis =new float[1];  ;
			
			Location.distanceBetween( WebSiteActivity.locData.getLatitude(),
					WebSiteActivity.locData.getLongitude(), 
					mGeoList.get(i).getPoint().getLatitudeE6() / 1000000.00, 
					mGeoList.get(i).getPoint().getLongitudeE6() / 1000000.00,dis);
			
			String temp = dis[0]/1000+"";
			if(temp.length()>0)
			{
				WebSiteActivity.distance  = temp.substring(0, temp.indexOf(".")+2);
				WebSiteActivity.tv_distance.setText("距离目前位置："
						+ WebSiteActivity.distance + "KM");
			}
			else
			{
				WebSiteActivity.tv_distance.setText("距离目前位置：无法定位当前位置");
			}
				
			
			
		} else {
			WebSiteActivity.tv_distance.setText("距离目前位置：无法定位当前位置");

		}
		
		
		
		WebSiteActivity.popviewTitle.setText(WebSiteActivity.webSiteInfo.get(
				WebSiteActivity.selectIndex).getShopName());
		WebSiteActivity.popviewSubTitle.setText(WebSiteActivity.webSiteInfo
				.get(WebSiteActivity.selectIndex).getShopAddress());

		// 更新气泡位置,并使之显示
		GeoPoint pt = mGeoList.get(i).getPoint();
		WebSiteActivity.mMapView.updateViewLayout(WebSiteActivity.mPopView,
				new MapView.LayoutParams(LayoutParams.WRAP_CONTENT,
						LayoutParams.WRAP_CONTENT, pt, 0,
						0 - WebSiteActivity.mPopView.getHeight() / 3,
						MapView.LayoutParams.BOTTOM_CENTER));

		WebSiteActivity.mMapView.getController().animateTo(
				mGeoList.get(i).getPoint());
		WebSiteActivity.mPopView.setVisibility(View.VISIBLE);

		return true;
	}

	@Override
	public boolean onTap(GeoPoint arg0, MapView arg1) {
		// TODO Auto-generated method stub
		// 消去弹出的气泡
		WebSiteActivity.mPopView.setVisibility(View.GONE);
		return super.onTap(arg0, arg1);
	}

	
}
